<template>
  <div class="cate">
    <p ref="p" @click="refsConsole">refs console click me</p>
    <div ref="dom">dom test</div>
    <div v-for="(item, i) in list" :key="i" :ref="(el) => {if (el) divs[i] = el;}">
      {{ item }}
    </div>
    <p>下面是子组件</p>
    <ArticleInfo ref='articleCom' :msg1="message1" :msg2="objCate.name" @click="changeMsg" @change="changeName"></ArticleInfo>
  </div>
</template>

<script>
import ArticleInfo from '../components/ArticleInfo.vue'
import { ref, reactive, onBeforeUpdate, onMounted } from 'vue'

export default {
  components: {
    ArticleInfo
  },
  setup () {
    const p = ref()
    const dom = ref(null)
    const articleCom = ref()
    const list = reactive([1, 2, 3])
    const divs = ref([])
    const message1 = ref('msg01')
    const message2 = ref('msg02')
    const objCate = reactive({ name: 'cate' })
    const that = this

    // 确保在每次更新之前重置ref
    onBeforeUpdate(() => {
      divs.value = []
    })

    onMounted(() => {
      console.log('p=', p.value)
      /* vue3获取ref的dom节点 */
      console.log('that = ', that)
      console.log('dom = ', dom)
      console.log('dom.value = ', dom.value) // vue3获取ref的dom节点
      console.log('list = ', list)
      console.log('divs = ', divs)
      console.log('divs.value = ', divs.value)
      console.log('objCate = ', objCate)
    })

    function changeMsg () {
      message1.value = 'mesg01'
      message2.value = 'mesg02'
      objCate.name = 'cate1'
    }

    function changeName () {
      alert('父组件被调用')
    }

    // setup 的返回值是一个对象, 将数据放入对象中返回
    return {
      p,
      dom,
      list,
      divs,
      message1,
      message2,
      changeMsg,
      objCate,
      changeName,
      articleCom
    }
  },
  methods: {
    refsConsole () {
      console.log('this.$refs.p = ', this.$refs.p)
      console.log('this.$refs.dom = ', this.$refs.dom)
      console.log('this.$refs.list = ', this.$refs.list)
      console.log('this.$refs.divs = ', this.$refs.divs)
      console.log('this.$refs.articleCom = ', this.$refs.articleCom)
      console.log('this.$refs.articleCom.msg1 = ', this.$refs.articleCom.msg1)
      console.log('this.$refs.articleCom.msg2 = ', this.$refs.articleCom.msg2)
      console.log('this.$refs.articleCom.info = ', this.$refs.articleCom.info)
      console.log('this.objCate = ', this.objCate)
      console.log('this.objCate.name = ', this.objCate.name)
      console.log('this.dom = ', this.dom)
      console.log('this.list = ', this.list)
      console.log('this.list[0] = ', this.list[0])
      console.log('this.divs = ', this.divs)
      console.log('this.divs[0] = ', this.divs[0])
    }
  }
}
</script>

<style>
.cate {
  background-color: #f1f1f1;
}
</style>
